package custom_http

import (
    "io"
    "net/http"
    "net/url"
    "time"
    "encoding/json"
    "fmt"
    "strings"
)

// HttpPostForm sends application/x-www-form-urlencoded form data and parses JSON response into T.
func HttpPostForm[T any](endpoint string, headers map[string]string, form url.Values) (T, error) {
    var zero T

    client := &http.Client{Timeout: 10 * time.Second}

    body := strings.NewReader(form.Encode())

    req, err := http.NewRequest("POST", endpoint, body)
    if err != nil {
        return zero, fmt.Errorf("创建请求失败: %w", err)
    }

    // Ensure correct content type for form submissions
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    for k, v := range headers {
        req.Header.Set(k, v)
    }

    resp, err := client.Do(req)
    if err != nil {
        return zero, fmt.Errorf("发起请求失败: %w", err)
    }
    defer resp.Body.Close()

    b, err := io.ReadAll(resp.Body)
    if err != nil {
        return zero, fmt.Errorf("读取响应失败: %w", err)
    }

    if resp.StatusCode < 200 || resp.StatusCode >= 300 {
        return zero, fmt.Errorf("HTTP 请求失败，状态码: %d, 响应: %s", resp.StatusCode, string(b))
    }

    var out T
    if err := json.Unmarshal(b, &out); err != nil {
        return zero, fmt.Errorf("响应 JSON 解析失败: %w", err)
    }
    return out, nil
}